# -*- coding: utf-8 -*-
from datetime import datetime
from decimal import Decimal

from flask import Blueprint, render_template, request, jsonify, current_app, redirect, url_for

from application import db
from common.libs.render_helper import getDictFilterField
from web.models.food.Food import Food
from web.models.food.FoodCat import FoodCat
from web.models.food.FoodStockChangeLog import FoodStockChangeLog

route_food = Blueprint('food_page', __name__)


@route_food.route("/index")
def index():
    # 查看美食列表
    resp_data = {}
    req = request.values
    query = Food.query
    if 'status' in req and int(req['status']) > -1:
        query = query.filter(Food.status == int(req['status']))
    if 'cat_id' in req and int(req['cat_id']) > 0:
        query = query.filter(Food.cat_id == int(req['cat_id']))
    cat_mapping = getDictFilterField(FoodCat, FoodCat.id, "id", [])
    list = query.order_by(Food.id.desc()).all()
    resp_data['list'] = list
    resp_data['search_con'] = req
    resp_data['status_mapping'] = current_app.config['STATUS_MAPPING']
    resp_data['cat_mapping'] = cat_mapping
    resp_data['current'] = 'index'
    return render_template("food/index.html", **resp_data)


@route_food.route("/info")
def info():
    # 查看美食详情
    resp_data = {}
    req = request.args
    id = int(req.get("id", 0))
    reback_url = url_for('food_page.index')
    if id < 1:
        return redirect(reback_url)
    info = Food.query.filter_by(id=id).first()
    if not info:
        return redirect(reback_url)
    # 修改库存
    stock_change_list = FoodStockChangeLog.query.filter(FoodStockChangeLog.food_id == id).order_by(
        FoodStockChangeLog.id.desc()).all()
    resp_data['info'] = info
    resp_data['current'] = 'index'
    resp_data['stock_change_list'] = stock_change_list
    return render_template("food/info.html", **resp_data)


@route_food.route("/set", methods=['GET', 'POST'])
def set():
    """添加或者修改美食"""
    if request.method == 'GET':
        context = {}
        req = request.args
        id = int(req.get('id', 0))
        # 依据美食id 去查询数据库表，假如info有值，则表示编辑(更新)
        info = Food.query.filter_by(id=id).first()
        if info and info.status != 1:
            return redirect(url_for('food_page.index'))
        # 查询美食分类列表
        cat_list = FoodCat.query.all()
        context['info'] = info  # info为None表示新增美食，不为None表示修改美食
        context['cat_list'] = cat_list
        context['current'] = 'index'
        return render_template("food/set.html", **context)
    # 以下是post请求执行的代码
    # 1.接收客户端传递过来的post请求参数
    resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
    req = request.values
    id = int(req['id']) if 'id' in req and req['id'] else 0
    cat_id = int(req['cat_id']) if 'cat_id' in req else 0
    name = req['name'] if 'name' in req else ''
    price = req['price'] if 'price' in req else ''
    main_image = req['main_image'] if 'main_image' in req else ''
    summary = req['summary'] if 'summary' in req else ''
    stock = int(req['stock']) if 'stock' in req else ''
    tags = req['tags'] if 'tags' in req else ''
    # 2.后端验证数据的合法性
    if cat_id < 1:
        resp['code'] = -1
        resp['msg'] = "请选择分类~~"
        return jsonify(resp)
    if name is None or len(name) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的名称~~"
        return jsonify(resp)
    if not price or len(price) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的售卖价格~~"
        return jsonify(resp)
    price = Decimal(price).quantize(Decimal('0.00'))
    if price <= 0:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的售卖价格~~"
        return jsonify(resp)
    if main_image is None or len(main_image) < 3:
        resp['code'] = -1
        resp['msg'] = "请上传封面图~~"
        return jsonify(resp)
    if summary is None or len(summary) < 3:
        resp['code'] = -1
        resp['msg'] = "请输入美食描述，并不能少于10个字符~~"
        return jsonify(resp)
    if stock < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的库存量~~"
        return jsonify(resp)
    if tags is None or len(tags) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入标签，便于搜索~~"
        return jsonify(resp)
    # 3.后台构建美食对象
    food_info = Food.query.filter_by(id=id).first()
    before_stock = 0
    if food_info:
        # 修改或者更新美食
        model_food = food_info
        before_stock = model_food.stock
    else:
        # 新增美食
        model_food = Food()
        model_food.status = 1
        model_food.created_time = datetime.now()
    # 4.不管是新增还是编辑(更新)美食，都要执行的操作
    model_food.cat_id = cat_id
    model_food.name = name
    model_food.price = price
    model_food.main_image = main_image
    model_food.summary = summary
    model_food.stock = stock
    model_food.tags = tags
    model_food.updated_time = datetime.now()
    # 5.提交到数据库
    db.session.add(model_food)
    db.session.commit()
    return jsonify(resp)


@route_food.route("/cat")
def cat():
    """查看美食分类列表"""
    # 取得传递过来的状态值status参数
    req = request.values
    query = FoodCat.query
    # 依据美食分类的状态值 查询 数据
    if 'status' in req and int(req['status']) > -1:
        query = query.filter(FoodCat.status == int(req['status']))
    cat_list = query.order_by(FoodCat.weight.desc(), FoodCat.id.desc()).all()
    context = {'cat_list': cat_list}
    # 搜索条件属性
    context['search_con'] = req
    context['status_mapping'] = current_app.config['STATUS_MAPPING']
    return render_template("food/cat.html", **context)


@route_food.route("/cat-set", methods=['GET', 'POST'])
def catSet():
    """添加或者修改美食分离"""
    if request.method == "GET":
        resp_data = {}
        req = request.args
        # 取得美食分类的id属性值
        id = int(req.get("id", 0))
        info = None
        if id:  # 是否传id值来区分是 编辑的请求 / 展示请求
            # 修改美食分类
            info = FoodCat.query.filter_by(id=id).first()
        resp_data['info'] = info
        resp_data['current'] = 'cat'
        return render_template("food/cat_set.html", **resp_data)

    # 以下是post请求执行的代码
    resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
    req = request.values
    id = req['id'] if 'id' in req else 0
    name = req['name'] if 'name' in req else ''
    weight = int(req['weight']) if ('weight' in req and int(req['weight']) > 0) else 1
    if name is None or len(name) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的分类名称~~"
        return jsonify(resp)
    # 依据美食分类取查询数据库相应的表，假如是新增操作，则返回值为None
    food_cat_info = FoodCat.query.filter_by(id=id).first()
    if food_cat_info:
        # 表示编辑操作
        model_food_cat = food_cat_info
    else:
        # 表示新增
        model_food_cat = FoodCat()
        model_food_cat.created_time = datetime.now()
    # 不管是新增还是编辑操作，都共同执行的代码
    model_food_cat.name = name
    model_food_cat.weight = weight
    model_food_cat.updated_time = datetime.now()
    # 把数据同步到数据库中
    db.session.add(model_food_cat)
    db.session.commit()
    return jsonify(resp)


@route_food.route('/cat-ops', methods=['POST'])
def cat_ops():
    resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
    req = request.values
    id = req['id'] if 'id' in req else 0
    act = req['act'] if 'act' in req else ''
    if not id:
        resp['code'] = -1
        resp['msg'] = "请选择要操作的账号~~"
        return jsonify(resp)
    if act not in ['remove', 'recover']:
        resp['code'] = -1
        resp['msg'] = "操作有误，请重试~~"
        return jsonify(resp)
    # 查询数据库获取美食分类对象，且更新状态(软删除、恢复)
    food_cat_info = FoodCat.query.filter_by(id=id).first()
    if not food_cat_info:
        resp['code'] = -1
        resp['msg'] = "指定分类不存在~~"
        return jsonify(resp)
    if act == "remove":
        food_cat_info.status = 0
    elif act == "recover":
        food_cat_info.status = 1
    food_cat_info.update_time = datetime.now()
    # 同步数据到数据库的表
    db.session.add(food_cat_info)
    db.session.commit()
    return jsonify(resp)


@route_food.route('/ops', methods=['POST'])
def ops():
    resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
    req = request.values
    id = req['id'] if 'id' in req else 0
    act = req['act'] if 'act' in req else ''
    if not id:
        resp['code'] = -1
        resp['msg'] = "请选择要操作的账号~~"
        return jsonify(resp)
    if act not in ['remove', 'recover']:
        resp['code'] = -1
        resp['msg'] = "操作有误，请重试~~"
        return jsonify(resp)
    food_info = Food.query.filter_by(id=id).first()
    if not food_info:
        resp['code'] = -1
        resp['msg'] = "指定美食不存在~~"
        return jsonify(resp)
    if act == "remove":
        food_info.status = 0
    elif act == "recover":
        food_info.status = 1
    food_info.updated_time = datetime.now()
    db.session.add(food_info)
    db.session.commit()
    return jsonify(resp)
